/**
 * 在输入框中插入表情
 * @param payload - 一个对象值，其中el属性为文本域元素，content为原生内容，emotion为需要插入的表情，count可选，为字数限制数
 * @returns string 返回插入表情后的内容
 */
const insertEmotion = (payload: {
  el: HTMLTextAreaElement;
  emotion: string;
  count?: number;
}): {
  isModify: boolean;
  content?: string;
} => {
  if (!(payload.el instanceof HTMLElement)) payload.el = (payload.el as any).textarea;
  const count: number = (payload.count && payload.count > 0) || payload.count === 0
    ? payload.count : 1800;
  const content: string = payload.el.value;
  /**
   * 将表情转换为[表情语]形式(如: '微笑'表情转换为[微笑])
   */
  const emotionString: string = `[${payload.emotion}]`;
  /**
   * 插入表情后的评论内容
   */
  let newContent: string = content;
  /**
   * 输入框光标悬停的首位置
   */
  const startPos: number = payload.el.selectionStart as number;
  /**
   * 如果用户选中一段文本时此时被选中文本末的位置
   */
  const endPos: number = payload.el.selectionEnd as number;
  newContent = newContent.slice(0, startPos) + emotionString +
    (startPos === endPos ? newContent.slice(startPos) : newContent.slice(endPos));

  // 如果超过字数则不作处理
  if (newContent.length > count) {
    // 正确显示光标位置
    setTimeout(() => {
      payload.el.setSelectionRange(startPos, endPos);
      payload.el.focus();
    }, 0)
    return {
      isModify: false
    }
  }

  // 输入框聚焦并且正确显示光标位置
  /**
   * 插入表情后此时光标应该出现的正确位置
   */
  const afterLocation: number = startPos + emotionString.length;
  // 正确显示光标位置
  setTimeout(() => {
    payload.el.setSelectionRange(afterLocation, afterLocation);
    payload.el.focus();
  }, 0)

  return {
    isModify: true,
    content: newContent,
  }
}

export default insertEmotion